<!--
入参：
boxType：组件类型（不传则默认饼图，"pie"）
         饼图："pie"  圆环图："pieCri"
          饼图-折线标注："pieLine"  圆环图-折线标注："pieCriLine"
legendData：图例数据 类型：[]
xData：目录数据      类型：[]
yData：展示数据数值  类型：[[],[]]   注意：饼图数值[[120, 132, 101, 134, 90, 230, 210]] 和legendData一一对应
yName：数值标题      类型：""
seriesName：饼图，圆环图legendData=[] 时 启用seriesName 类型:[]
grName:圆环图文字 \n可换行
grNameTop：圆环图文字的上下位置
criRadius：圆环图的环状大小
lineLableStyle:折线标注使用样式
legendConfig：legend的配置信息
grid：图像的缩放偏移
lineShow：是否显示标注线
labelShow：是否显示标注
 示例：
boxType="pie"
      legendData= ['邮件营销','联盟广告','视频广告','直接访问','搜索引擎']
     xData=[]
     yName="";
     title='饼图'
     yData=[[120, 132, 101, 134, 90]] 此处120对应'邮件营销'，132对应'联盟广告',以此类推。
-->
<template>
  <div class="echarts">
    <div ref="echartsBox" class="echartsBox" />
  </div>
</template>
<script>
import * as echarts from 'echarts';
export default {
  name: 'echartsPie',
  props: {
    'legendConfig': { type: [Object], default: function() {
        // orient:"horizontal"/"vertical"
        // align:"auto"/"left"/"right"
        // left:"left"/"center"/"right"/px值/百分比值
        // top:'top'/ 'middle'/ 'bottom'/px值/百分比值
        // auto:均可替换成一定的px值/百分比值
        return {
          left: 'center', right: 'auto', top: 'bottom', bottom: '30px', orient: 'horizontal', width: 'auto', height: 'auto',
          align: 'auto'
        };
      } },
    'grid': { type: [Object], default: function() {
        return {
          top: '30px', left: '4%', right: '4%', bottom: '0px', containLabel: true };
      } },
    'lineLableStyle': { type: [Object], default: function() {
        return {
          // alignTo:'none'/'labelLine'/'edge'
          alignTo: 'none', position: 'outer', margin: '10' };
      } },
    'radius': { type: String, default: function() { return '80%'; } },
    'criRadius': { type: Array, default: function() { return ['30%', '50%']; } },
    'centerPie': { type: Array, default: function() { return ['30%', '50%']; } },
    'lineShow': { type: Boolean, default: function() { return true; } },
    'labelShow': { type: Boolean, default: function() { return false; } },
    'grNameLeft': { type: String, default: function() { return '30%'; } },
    'grNameTop': { type: String, default: function() { return '36%'; } },
    'grName': { type: String, default: function() { return ''; } },
    'legendData': { type: Array, default: function() { return []; } },
    'xData': { type: Array, default: function() { return []; } },
    'yData': { type: Array, default: function() { return []; } },
    'title': { type: String, default: function() { return ''; } },
    'yName': { type: String, default: function() { return ''; } },
    'boxType': { type: String, default: function() { return 'line'; } },
    'seriesName': { type: [Array, String], default: function() { return ''; } },
    'color': { type: [Array, String], default: function() { return ''; } }
  },
  data() {
    return {
      series: []
    };
  },
  computed: {

    rtColor: function() {
      if (this.color) {
        return this.color;
      } else {
        return [
          /* "#12B5B0",
              "#DFC050",
              "#5AC4C7",
              "#DF8B6F",
              "#FFB596",
              "#B6A2DE",
              "#2EC7C9",
              "#C6F4F4",
              "#2199BB",
              "#f9d1BC"*/
          '#2F8EE0',
          '#6FD088',
          '#F85778',
          '#FFBC47',
          '#287dc6',
          '#52aa69',
          '#d64c68',
          '#e19d26',
          '#34a1ff',
          '#81f29e',
          '#ff819b',
          '#fea407'
        ];
      }
    },
    // echars数据处理
    option() {
      // 饼图Option
      const pieOption = this.getPieOption();
      // 饼图
      if (this.boxType == null || this.boxType === 'pie') {
        return this.getPie(pieOption);
      } else if (this.boxType === 'pieLine') {
        return this.getPieLine(pieOption);
      } else if (this.boxType === 'pieCri') {
        return this.getPieCri(pieOption);
      } else if (this.boxType === 'pieCriLine') {
        return this.getPieCriLine(pieOption);
      } else {
        return pieOption;
      }
    }
  },
  watch: {
    option: {
      handler() {
        echarts.init(this.$refs.echartsBox).resize();
        echarts.init(this.$refs.echartsBox).setOption(this.option, true);
      }
    }
  },
  mounted() {
    const thir = this;
    window.onresize = function() {
      thir.watchChangeSize();
    };
    echarts.init(this.$refs.echartsBox).setOption(this.option, true);
    echarts.init(this.$refs.echartsBox).resize();
    echarts.init(this.$refs.echartsBox).on('click',(params)=> {
      this.$emit('echartsPie',params)
    })
  },
  methods: {
    watchChangeSize() {
      echarts.init(this.$refs.echartsBox).resize();
    },
    init() {
      echarts.init(this.$refs.echartsBox).setOption(this.option, true);
    },
    setSeries(obj) {
      this.series.push(obj);
    },
    resetSeries() {
      this.series = [];
    },
    getPieOption() {
      const targer = this;
      return {
        color: targer.rtColor,
        title: {
          textStyle: { color: '#333', fontSize: '12px',align:'center'},
          text: this.title,
          top:'51%',
          x: '25%'
        },
        tooltip: {
          transitionDuration: 0,
          position: 'inside',
          fontFamily: 'Arial, SimHei',
          extraCssText: 'z-index:99999',
          trigger: 'item',
          formatter:function(params) {
            return params.name+":" + params.value +' '+ params.percent+'%'
          }
        },
        legend: {
          textStyle: {
            color: '#b8b8b8',
            fontSize: '12px',
            fontFamily: 'Arial, SimHei'
          },
          formatter:function(name) {
            var total = 0; // 用于计算总数
            var target; // 遍历拿到数据
            for (var i = 0; i < targer.series[0].data.length; i++) {
              total += targer.series[0].data[i].value;
              if (targer.series[0].data[i].name == name) {
                target = targer.series[0].data[i].value;
              }
            }
            var v = ((target / total) * 100).toFixed(0);
            if(total == 0) {
				// return name +'   '+ target 
              return name +'   '+ target +'   '+0+'%';
            }else {
				 // return name +'   '+ target
              return name +'   '+ target +'   '+v+'%';
            }

          },
          data: this.legendData,
          ...this.legendConfig
        },

        series: []
      };
    },
    getPie(pieOption) {
      const pieData = [];
      const pData = this.yData[0] || [];
      for (let i = 0; i < pData.length; i++) {
        if (this.legendData.length) {
          pieData.push({ value: pData[i], name: this.legendData[i] });
        } else {
          pieData.push({ value: pData[i], name: this.seriesName[i] });
        }
      }
      this.resetSeries();
      if (this.legendData.length) {
        this.setSeries({
          type: 'pie',
          radius: this.radius,
          center: ['50%', '40%'],
          data: pieData,
          ...this.grid,
          itemStyle: {
            normal: {
              label: {
                color: '#b8b8b8',
                show: this.labelShow,
                fontSize: 12,
                position: 'inside',
                formatter: '{d}%'
              },
              labelLine: {
                show: false
              }
            }
          }
        });
      } else {
        this.setSeries({
          type: 'pie',
          radius: this.radius,
          center: ['50%', '60%'],
          data: pieData,
          ...this.grid,
          itemStyle: {
            normal: {
              label: {
                color: '#b8b8b8',
                show: this.labelShow,
                fontSize: 12,
                position: 'inside',
                formatter: '{d}%'
              },
              labelLine: {
                show: false
              }
            }
          }
        });
      }
      pieOption.series = this.series;
      return pieOption;
    },
    getPieCri(pieOption) {
		console.log(pieOption,"pieOption")
      const pieData = [];
      const pData = this.yData[0];
      for (let i = 0; i < pData.length; i++) {
        if (this.legendData.length) {
          pieData.push({ value: pData[i], name: this.legendData[i] });
        } else {
          pieData.push({ value: pData[i], name: this.seriesName[i] });
        }
      }
      this.resetSeries();
      if (this.legendData.length) {
        this.setSeries({
          type: 'pie',
          radius: this.criRadius,
          center: this.centerPie,
          data: pieData,
          ...this.grid,
          itemStyle: {
            normal: {
              borderColor: '#fff',
              borderWidth: 2,
              label: {
                color: '#b8b8b8',
                show: this.labelShow,
                fontSize: 12,
                position: 'inside',
                formatter: '{d}%'
              },
              labelLine: {
                normal: {
                  show: false
                }
              }
            }
          }
        });
      } else {
        this.setSeries({
          type: 'pie',
          radius: this.criRadius,
          center: ['35%', '50%'],
          data: pieData,
          ...this.grid,
          itemStyle: {
            normal: {
              label: {
                color: '#b8b8b8',
                show: this.labelShow,
                fontSize: 12,
                position: 'inside',
                formatter: '{d}%'
              },
              labelLine: {
                normal: {
                  show: this.lineShow,
                  smooth: 1,
                  length: 5,
                  length2: 1
                }
              }
            }
          }

        });
      }
      if (this.grName) {
        const graphic = [
          {
            // 环形图中间添加文字
            type: 'text', // 通过不同top值可以设置上下显示
            left: this.grNameLeft,
            top: this.grNameTop,
            style: {
              text: this.grName, // "环图中添加颜色" + "\n" + "和series平级",
              textAlign: 'center',
              fill: '#333333', // 文字的颜色
              width: 30,
              height: 30,
              fontSize: 22,
              fontWeight: 'bold',
              fontFamily: 'Microsoft YaHei'
            }
          }
        ];
        pieOption.graphic = graphic;
      }
      pieOption.series = this.series;
      return pieOption;
    },
    getPieLine(pieOption) {
      const pieData = [];
      const pData = this.yData[0] || [];
      for (let i = 0; i < pData.length; i++) {
        if (this.legendData.length) {
          pieData.push({ value: pData[i], name: this.legendData[i] });
        } else {
          pieData.push({ value: pData[i], name: this.seriesName[i] });
        }
      }
      this.resetSeries();
      if (this.legendData.length) {
        this.setSeries({
          type: 'pie',
          radius: '55%',
          center: ['50%', '40%'],
          data: pieData,
          ...this.grid,
          label: { ...this.lineLableStyle },
          labelLine: {
            normal: {
              show: this.lineShow,
              smooth: 0,
              length: 6,
              length2: 6
            }
          }
        });
      } else {
        this.setSeries({
          type: 'pie',
          radius: '55%',
          center: ['50%', '60%'],
          data: pieData,
          ...this.grid,
          label: { ...this.lineLableStyle },
          labelLine: {
            normal: {
              show: this.lineShow,
              smooth: 0,
              length: 6,
              length2: 6
            }
          }
        });
      }
      pieOption.series = this.series;
      return pieOption;
    },
    getPieCriLine(pieOption) {
      const pieData = [];
      const pData = this.yData[0];
      for (let i = 0; i < pData.length; i++) {
        if (this.legendData.length) {
          pieData.push({ value: pData[i], name: this.legendData[i] });
        } else {
          pieData.push({ value: pData[i], name: this.seriesName[i] });
        }
      }
      this.resetSeries();
      if (this.legendData.length) {
        this.setSeries({
          type: 'pie',
          radius: this.criRadius,
          center: ['50%', '50%'],
          data: pieData,
          label: { ...this.lineLableStyle },
          ...this.grid,
          labelLine: {
            normal: {
              show: this.lineShow,
              smooth: 0,
              length: 10,
              length2: 60
            }
          }
        });
      } else {
        this.setSeries({
          type: 'pie',
          radius: this.criRadius,
          center: ['50%', '60%'],
          data: pieData,
          label: { ...this.lineLableStyle },
          ...this.grid,
          labelLine: {
            normal: {
              show: this.lineShow,
              smooth: 0,
              length: 6,
              length2: 6
            }
          }

        });
      }
      if (this.grName) {
        const graphic = [
          {
            // 环形图中间添加文字
            type: 'text', // 通过不同top值可以设置上下显示
            left: 'center',
            top: this.grNameTop,
            style: {
              text: this.grName, // "环图中添加颜色" + "\n" + "和series平级",
              textAlign: 'center',
              fill: '#b8b8b8', // 文字的颜色
              width: 30,
              height: 30,
              fontSize: 15,
              fontFamily: 'Microsoft YaHei'
            }
          }
        ];
        pieOption.graphic = graphic;
      }
      pieOption.series = this.series;
      return pieOption;
    }
  }
};
</script>
<style scoped>
.echarts {
  width: 100%;
  height: 100%;
}
.echartsBox {
  width: 100%;
  height: 100%;
}
</style>
